<template>
    <div class="wrapper">
        <div class="chat-wrapper">
            <div class="header">
                <span>Talk a talk - {{ curUser.name }}</span> 
                <a @click="logout">logout</a>
            </div>
            <div class="content">
                <div class="chat-list ">
                    <UserList :onlineUsers="onlineUsers"/>
                </div>
                <div class="chat-record">
                    <div class="chat-content" ref="chat">
                        <UserWithMsg 
                            v-for="(msgItem,idx) in msgList"
                            :key="idx"
                            v-bind="msgItem"
                        />
                    </div>
                    <div class="edit-part">
                        <a-textarea 
                            placeholder="回车发送"
                            :style="{background: 'transparent',border: 'none',height: '15vh'}"
                            @keydown="handleSendMsg"
                            :value="chatMsg"
                            @change="v => this.chatMsg = v.target.value"
                        />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
console.log('loading chat');
import UserList from './components/UserList'
import UserWithMsg from './components/UserWithMsg'
import { Socket } from '@/utils/socket'
import { RECIEVE,ONLINE_USER } from '@/utils/event-const'
import { getUser } from '@/utils/user'
import { getHistoryMsg as _getHistoryMsg } from '@/service/message'
import _ from 'lodash'

export default {
    name: 'chat',
    components:{
        UserList,
        UserWithMsg
    },
    mounted(){
    },
    data(){
        return {
            chatIo: null,
            chatMsg: '',
            msgList:[],
            onlineUsers: [],
            curUser: getUser()
        }
    },
    mounted(){
        this.initSocket()
        this.getHistoryMsg()
    },
    destroyed(){
        this.chatIo.close()
    },
    methods:{
        initSocket(){
            this.chatIo = new Socket()
            this.chatIo.connect()
            this.chatIo.on(RECIEVE,data => {
                this.msgList = [...this.msgList,JSON.parse(data)]
                this.$nextTick(function(){
                    this.$refs.chat.scrollTo(0,Number.MAX_SAFE_INTEGER)
                })
            })
            // 连接成功后获取当前的在线用户列表
            this.chatIo.on(ONLINE_USER,data => {
                console.log(data);
                this.onlineUsers = data
            })
        },
        async getHistoryMsg(){
            try {
                const res = await _getHistoryMsg()
                const handleData = res.data.map(item => ({
                    msg: item.content,
                    userName: item.sendUser.userName,
                    userId: item.sendUser.id,
                    sendTime: +item.sendTime
                }))
                this.msgList = _.orderBy(handleData,['sendTime'],['asc'])
            } catch (error) {
                
            }
        },
        handleSendMsg(e){
            if(e.keyCode !== 13){
                return
            }
            const user = getUser()
            const sendData = {
                userName: user.name,
                msg: this.chatMsg,
                userId: user.id,
                send_user_id: user.id,
                content: this.chatMsg,
                send_time: Date.now()
            }
            this.chatIo.emit('message',JSON.stringify(sendData),data => {
                this.chatMsg = ''
            })
        },
        logout(){
            localStorage.clear()
            this.$router.push({
                path: '/login'
            })
        }
    }
}
</script>

<style lang='less' scoped>
    .wrapper {
        height: 100vh;
        overflow: hidden;
        background: url('../../assets/bg01.jpg') no-repeat center;
        background-attachment: fixed;
        background-size: cover;
        position: relative;

        .chat-wrapper {
            position: absolute;
            width: 80vw;
            height: 80vh;
            background: #fff;
            border-radius: 5px;
            // border: 2px solid rgba(255, 255, 255, .5);
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            box-shadow: 1px 4px 12px rgb(0 0 0 / 15%);
        }

        .header {
            height: 60px;
            line-height: 60px;
            padding: 0 24px;
            background: #008cee;
            border-radius: 5px 5px 0 0;
            color: #fff;
            font-size: 16px;
            display: flex;
            justify-content: space-between;

            a {
                color: #fff;
            }
        }

        .content {
            height: calc(80vh - 60px);
            display: flex;

            .chat-list{
                width: 250px;
                overflow: auto;
                background: #f5f9ff;
                border-right: 1px solid #ccc;
            }
            .chat-record {
                flex: 7;

                .chat-content {
                    height: calc(65vh - 60px);
                    background: #f8fbff;
                    overflow: auto;
                }
                .edit-part {
                    border-top: 1px solid #ccc;
                    height: 15vh;
                    background: #f5f9ff;
                }
            }
        }
    }
</style>